import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Progress } from '@/components/ui/progress';
import { Badge } from '@/components/ui/badge';
import {
  Activity,
  Cpu,
  HardDrive,
  MemoryStick,
  Network,
  Server,
  Wifi,
  AlertTriangle,
  CheckCircle,
  XCircle,
  Clock
} from 'lucide-react';

// 系统指标接口
interface SystemMetrics {
  cpu: {
    usage: number;
    cores: number;
    temperature: number;
  };
  memory: {
    used: number;
    total: number;
    usage: number;
  };
  disk: {
    used: number;
    total: number;
    usage: number;
  };
  network: {
    upload: number;
    download: number;
    latency: number;
  };
  services: {
    name: string;
    status: 'running' | 'stopped' | 'error';
    uptime: string;
    memory: number;
  }[];
  uptime: string;
  lastUpdate: Date;
}

// 系统健康状态
interface SystemHealth {
  overall: 'healthy' | 'warning' | 'critical';
  issues: {
    type: 'warning' | 'error';
    message: string;
    timestamp: Date;
  }[];
}

interface SystemMonitorProps {
  className?: string;
}

/**
 * 系统监控组件
 * 提供实时的系统性能指标和健康状态监控
 */
export const SystemMonitor: React.FC<SystemMonitorProps> = ({ className }) => {
  const [metrics, setMetrics] = useState<SystemMetrics | null>(null);
  const [health, setHealth] = useState<SystemHealth | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  // 模拟获取系统指标数据
  const fetchSystemMetrics = (): SystemMetrics => {
    return {
      cpu: {
        usage: Math.floor(Math.random() * 80) + 10,
        cores: 8,
        temperature: Math.floor(Math.random() * 20) + 45
      },
      memory: {
        used: Math.floor(Math.random() * 12) + 4,
        total: 16,
        usage: 0
      },
      disk: {
        used: Math.floor(Math.random() * 200) + 300,
        total: 512,
        usage: 0
      },
      network: {
        upload: Math.floor(Math.random() * 50) + 10,
        download: Math.floor(Math.random() * 100) + 20,
        latency: Math.floor(Math.random() * 20) + 5
      },
      services: [
        {
          name: 'Web Server',
          status: Math.random() > 0.1 ? 'running' : 'error',
          uptime: '15d 8h 32m',
          memory: Math.floor(Math.random() * 500) + 100
        },
        {
          name: 'Database',
          status: Math.random() > 0.05 ? 'running' : 'error',
          uptime: '15d 8h 30m',
          memory: Math.floor(Math.random() * 800) + 200
        },
        {
          name: 'Cache Server',
          status: Math.random() > 0.15 ? 'running' : 'stopped',
          uptime: '15d 8h 28m',
          memory: Math.floor(Math.random() * 300) + 50
        },
        {
          name: 'Message Queue',
          status: Math.random() > 0.1 ? 'running' : 'error',
          uptime: '15d 8h 25m',
          memory: Math.floor(Math.random() * 200) + 80
        }
      ],
      uptime: '15d 8h 32m',
      lastUpdate: new Date()
    };
  };

  // 计算系统健康状态
  const calculateSystemHealth = (metrics: SystemMetrics): SystemHealth => {
    const issues: SystemHealth['issues'] = [];
    let overall: SystemHealth['overall'] = 'healthy';

    // 检查CPU使用率
    if (metrics.cpu.usage > 80) {
      issues.push({
        type: 'warning',
        message: `CPU使用率过高: ${metrics.cpu.usage}%`,
        timestamp: new Date()
      });
      overall = 'warning';
    }

    // 检查内存使用率
    if (metrics.memory.usage > 85) {
      issues.push({
        type: 'error',
        message: `内存使用率过高: ${metrics.memory.usage}%`,
        timestamp: new Date()
      });
      overall = 'critical';
    }

    // 检查磁盘使用率
    if (metrics.disk.usage > 90) {
      issues.push({
        type: 'error',
        message: `磁盘使用率过高: ${metrics.disk.usage}%`,
        timestamp: new Date()
      });
      overall = 'critical';
    }

    // 检查服务状态
    const errorServices = metrics.services.filter(s => s.status === 'error');
    if (errorServices.length > 0) {
      issues.push({
        type: 'error',
        message: `${errorServices.length}个服务异常`,
        timestamp: new Date()
      });
      overall = 'critical';
    }

    const stoppedServices = metrics.services.filter(s => s.status === 'stopped');
    if (stoppedServices.length > 0) {
      issues.push({
        type: 'warning',
        message: `${stoppedServices.length}个服务已停止`,
        timestamp: new Date()
      });
      if (overall === 'healthy') overall = 'warning';
    }

    return { overall, issues };
  };

  // 更新系统指标
  const updateMetrics = () => {
    const newMetrics = fetchSystemMetrics();
    // 计算使用率百分比
    newMetrics.memory.usage = Math.round((newMetrics.memory.used / newMetrics.memory.total) * 100);
    newMetrics.disk.usage = Math.round((newMetrics.disk.used / newMetrics.disk.total) * 100);
    
    setMetrics(newMetrics);
    setHealth(calculateSystemHealth(newMetrics));
    setIsLoading(false);
  };

  // 初始化和定时更新
  useEffect(() => {
    updateMetrics();
    const interval = setInterval(updateMetrics, 5000); // 每5秒更新一次
    return () => clearInterval(interval);
  }, []);

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'running':
        return <CheckCircle className="h-4 w-4 text-green-500" />;
      case 'stopped':
        return <XCircle className="h-4 w-4 text-yellow-500" />;
      case 'error':
        return <AlertTriangle className="h-4 w-4 text-red-500" />;
      default:
        return <Clock className="h-4 w-4 text-gray-500" />;
    }
  };

  // 获取健康状态徽章
  const getHealthBadge = (status: SystemHealth['overall']) => {
    switch (status) {
      case 'healthy':
        return <Badge className="bg-green-100 text-green-800">健康</Badge>;
      case 'warning':
        return <Badge className="bg-yellow-100 text-yellow-800">警告</Badge>;
      case 'critical':
        return <Badge className="bg-red-100 text-red-800">严重</Badge>;
      default:
        return <Badge className="bg-gray-100 text-gray-800">未知</Badge>;
    }
  };

  if (isLoading || !metrics || !health) {
    return (
      <div className={`space-y-4 ${className}`}>
        <div className="animate-pulse">
          <div className="h-32 bg-gray-200 rounded-lg"></div>
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* 系统健康状态概览 */}
      <Card>
        <CardHeader className="pb-3">
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg font-semibold flex items-center gap-2">
              <Server className="h-5 w-5" />
              系统健康状态
            </CardTitle>
            {getHealthBadge(health.overall)}
          </div>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            {/* CPU */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Cpu className="h-4 w-4 text-blue-500" />
                <span className="text-sm font-medium">CPU</span>
              </div>
              <Progress value={metrics.cpu.usage} className="h-2" />
              <div className="text-xs text-gray-600">
                {metrics.cpu.usage}% ({metrics.cpu.cores}核)
              </div>
            </div>

            {/* 内存 */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <MemoryStick className="h-4 w-4 text-green-500" />
                <span className="text-sm font-medium">内存</span>
              </div>
              <Progress value={metrics.memory.usage} className="h-2" />
              <div className="text-xs text-gray-600">
                {metrics.memory.used}GB / {metrics.memory.total}GB
              </div>
            </div>

            {/* 磁盘 */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <HardDrive className="h-4 w-4 text-purple-500" />
                <span className="text-sm font-medium">磁盘</span>
              </div>
              <Progress value={metrics.disk.usage} className="h-2" />
              <div className="text-xs text-gray-600">
                {metrics.disk.used}GB / {metrics.disk.total}GB
              </div>
            </div>

            {/* 网络 */}
            <div className="space-y-2">
              <div className="flex items-center gap-2">
                <Network className="h-4 w-4 text-orange-500" />
                <span className="text-sm font-medium">网络</span>
              </div>
              <div className="text-xs text-gray-600">
                ↑ {metrics.network.upload}MB/s
              </div>
              <div className="text-xs text-gray-600">
                ↓ {metrics.network.download}MB/s
              </div>
            </div>
          </div>

          {/* 系统运行时间 */}
          <div className="mt-4 pt-4 border-t">
            <div className="flex items-center justify-between text-sm">
              <span className="text-gray-600">系统运行时间: {metrics.uptime}</span>
              <span className="text-gray-600">
                最后更新: {metrics.lastUpdate.toLocaleTimeString()}
              </span>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 服务状态 */}
      <Card>
        <CardHeader className="pb-3">
          <CardTitle className="text-lg font-semibold flex items-center gap-2">
            <Activity className="h-5 w-5" />
            服务状态
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="space-y-3">
            {metrics.services.map((service, index) => (
              <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div className="flex items-center gap-3">
                  {getStatusIcon(service.status)}
                  <div>
                    <div className="font-medium">{service.name}</div>
                    <div className="text-sm text-gray-600">运行时间: {service.uptime}</div>
                  </div>
                </div>
                <div className="text-right">
                  <div className="text-sm font-medium">{service.memory}MB</div>
                  <div className="text-xs text-gray-600">内存使用</div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* 系统警告 */}
      {health.issues.length > 0 && (
        <Card>
          <CardHeader className="pb-3">
            <CardTitle className="text-lg font-semibold flex items-center gap-2 text-red-600">
              <AlertTriangle className="h-5 w-5" />
              系统警告
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {health.issues.map((issue, index) => (
                <div key={index} className="flex items-center gap-3 p-3 bg-red-50 rounded-lg">
                  <AlertTriangle className={`h-4 w-4 ${
                    issue.type === 'error' ? 'text-red-500' : 'text-yellow-500'
                  }`} />
                  <div className="flex-1">
                    <div className="font-medium">{issue.message}</div>
                    <div className="text-sm text-gray-600">
                      {issue.timestamp.toLocaleTimeString()}
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
};

export default SystemMonitor;